package com.letter.otools.day.todo;

import android.app.Activity;
import android.content.Intent;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.letter.otools.day.BaseFragment;
import com.letter.otools.day.R;

import org.litepal.FluentQuery;
import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

public class TodoFragment extends BaseFragment {
    private MaterialToolbar toolbar;
    private RecyclerView TodoRecyclerView;
    private FloatingActionButton fabAdd;

    private List<Todo> TodoList = new ArrayList<>();

    @Override
    protected int getLayout() {
        return R.layout.todo_list;
    }

    @Override
    protected void onResultData(int resultCode, Intent intent) {
        if (resultCode == Activity.RESULT_OK) {
            this.loadData(null, true);
        }
        super.onResultData(resultCode, intent);
    }

    @Override
    protected void initView(View view) {
        registerForActivityResult();
        fabAdd.setOnClickListener(v -> {
            launchForResult(TodoAddActivity.class);
        });
        TodoRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        TodoRecyclerView.setAdapter(TodoAdapter = new TodoAdapter(TodoList));
        TodoAdapter.setPositionListener((p, d) -> {
            switch (p) {
                case 1:
                    Intent intent = new Intent(getActivity(), TodoDetailActivity.class);
                    intent.putExtra("TodoId", ((Todo) d).getId());
                    launchForResult(intent);
                    break;
            }
        });
        loadData(null, true);
    }

    void loadData(Integer type, boolean notify) {
        TodoList.clear();
        FluentQuery fluentQuery = LitePal.order("id desc");
        if (type != null) {
            fluentQuery.where("type = ?", String.valueOf(type));
        }
        List<Todo> anniversaryList = fluentQuery.find(Todo.class);
        if (anniversaryList != null && !anniversaryList.isEmpty()) {
            this.TodoList.addAll(anniversaryList);
        }

        if (notify) {
            TodoAdapter.notifyDataSetChanged();
        }
    }

    TodoAdapter TodoAdapter;

    @Override
    public void initBinder(View view) {
        toolbar = view.findViewById(R.id.toolbar);
        TodoRecyclerView = view.findViewById(R.id.diaryRecyclerView);
        fabAdd = view.findViewById(R.id.fabAdd);
    }
}
